<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/10/27
 * Time: 下午3:35
 */

namespace Admin\Mobile\Controllers;


use Admin\Models\bpm\XHBpmPlanContent;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\msg\XhmsgNotice;
use Admin\Models\msg\XhmsgRecord;
use Admin\Models\sys\XhsysEnum;
use Helpers\Assets;
use Helpers\Main;
use Helpers\UserPower;
use Modules\Power;
use Phalcon\Exception;

class HomeController extends ControllerBase
{

    private static $enums = [
        'iNoType' => [1 => '通知', 2 => '公告'],
    ];


    /**
     * 获取node详情
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/24
     */
    public function getNodeDetailAction()
    {
        $iBPCId = $this->request->getPost('iBPCId');
        $node = XHBpmPlanContent::findFirst([
            'conditions' => 'bDelete=0 AND iBPCId=:iBPCId:',
            'bind' => ['iBPCId' => $iBPCId],
        ])->toArray();
        return $this->sendJsonResponse($node);
    }

    /**
     * 初始化
     *
     * create by dale 20171215
     */
    public function initAction()
    {
        $initArr = [];
        $notice = $this->getNotice();//通知公告
        $initArr['notice'] = ['tag'=>'notice','class'=>'clickNotice','data'=>$notice,
            'power' => Power::exist('Msg') ];
        $appMsg = $this->getMsg(4);
        $initArr['appMsg'] = ['tag'=>'4','class'=>'clickMsg','data'=>$appMsg,'power' => Power::exist('Article_App')];
        $tchMsg = $this->getMsg(5);
        $initArr['tchMsg'] = ['tag'=>'5','class'=>'clickMsg','data'=>$tchMsg,'power' => Power::exist('Article_Book')];
        $planMsg = $this->getMsg(6);
        $initArr['planMsg'] = ['tag'=>'6','class'=>'clickMsg','data'=>$planMsg,'power' => Power::exist('Article_Plan')];
        $pClass = $this->getPClass();
        $initArr['pClass'] = ['tag'=>'7','class'=>'clickClass','data'=>$pClass,
            'power' => Power::exist('School_Teacher_PublicClass')];
        return json_encode($initArr);

    }

    public function classDetailAction(){
        try{
            $iPCId = $this->request->getQuery('iPCId') or die('缺少参数');
            $this->view->pick('home/classDetail');
            Assets::importJs('../ims/js/myTool.js');
//        Assets::importJs('js/tch/home.js');
            $builder=$this->modelsManager->createBuilder()
                ->columns("p.iPCId,p.iUserId,p.tStartTime,p.iPCType,p.mContent,u.iSchoolId,s.sSchoolName,u.sUserName,
                       p.sPlace ,p.iStuNum,p.iAttendNum,p.sAttendClass,p.mAttendences,p.mDesc,p.iRunChargeId,
                       p.iAtClassChargeId,p.iWebChargeId,p.iTechChargeId,p.iMarkChargeId,p.mEvaluate,
                       p.iEvalId,p.tEvalTime,up.sSelfPhone")
                ->from(['p'=>'Admin\Models\school\XhschoolPublicClass'])
                ->where('p.bDelete=0 AND iPCId=:iPCId:',array('iPCId'=>$iPCId));
            $builder->leftJoin('Admin\Models\user\XhsysUser','u.iUserId=p.iUserId','u')
                ->leftJoin('Admin\Models\user\XhsysUser','p.iEvalId=up.iUserId','up')
                ->leftJoin('Admin\Models\school\XhschoolInfo','s.iSchoolId=u.iSchoolId','s');
            $info = $builder->getQuery()->execute()->toArray();

            $info[0]['tStartTime'] = date('Y-m-d h:i',strtotime($info[0]['tStartTime']));

            $this->runPhoneById($info,['iRunChargeId'=>'runPhone','iAtClassChargeId'=>'atcPhone','iWebChargeId'=>'webPhone','iTechChargeId'=>'techPhone','iMarkChargeId'=>'markPhone'],true);
            $this->runStaffNameById($info,['iAtClassChargeId'=>'iAtClassChargeId','iRunChargeId'=>'iRunChargeId','iWebChargeId'=>'iWebChargeId','iTechChargeId'=>'iTechChargeId','iMarkChargeId'=>'iMarkChargeId'],true);
            $info = $info[0];

            $this->view->setVars([
                'info'=>$info,
            ]);
        }catch (\Exception $e){
            die($e->getMessage());
        }
    }

    /**
     * 更多消息
     *
     * created by dale 20171127
     */
    public function moreClassAction(){
        Assets::easyUIMobile();
        $this->view->pick('tp/listView');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/home/moreClass.js');
    }

    /**
     * 获取更多class
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20171216
     */
    public function getMoreClassAction(){
        return $this->sendJsonResponse($this->getPClass(true));
    }


    private function getPClass($more=false){
        $builder=$this->modelsManager->createBuilder()
            ->columns("p.iPCId,p.iUserId,p.tStartTime,p.iPCType,u.iSchoolId,s.sSchoolName,u.sUserName")
            ->from(['p'=>'Admin\Models\school\XhschoolPublicClass'])
            ->where('p.bDelete=0');
        $builder->andWhere('p.tStartTime >= :today:',array('today'=>date('Y-m-d',strtotime('now'))))->orderBy('p.tStartTime desc,p.tCreateDate');
        $builder->leftJoin('Admin\Models\user\XhsysUser','u.iUserId=p.iUserId','u')
            ->leftJoin('Admin\Models\school\XhschoolInfo','s.iSchoolId=u.iSchoolId','s');
            if(!$more){
                $builder->limit(2);
            }
        $pClasses=$builder->getQuery()->execute()->toArray();
        $enums['iPCType'] = XhsysEnum::getEnumByNodeName('公开课类别');
        $pClasses = array_reverse($pClasses); //倒置数组
        foreach ($pClasses as $index=>$pClass){
            $pClasses[$index]['iPCType']=$enums['iPCType'][$pClass['iPCType']];
            $pClasses[$index]['tStartTime']=date('Y-m-d h:i',strtotime($pClass['tStartTime']));
        }
        return $pClasses;
    }



    /**
     * 获取通知信息
     *
     * @return array
     *
     * created by dale 2017/10/27
     * modify by dale 20171215
     */
    private function getNotice()
    {
        $this->view->disable();
        $more = $this->request->getPost('more', 'string');
        $userId = Main::getLoginUserInfo('userId');

        $builder = $this->modelsManager->createBuilder()
            ->columns("n.iNoId,iNoType,sTitle,tTime,sUserIds")
            ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
            ->where('n.bDelete=0')->orderBy('n.tTime desc');
        if (!$more) {
            $builder->limit(2);
        }
        if(!UserPower::checkUserPower('Msg_NoAfList_All')){  //具有全部查看权限
            $builder->andWhere('( n.iNoType=1 AND sUserIds like :userId: ) OR n.iNoType=2',array('userId'=>'%,'.$userId.',%'));
        };
        $notices = $builder->getQuery()->execute()->toArray();

        $recs=XhmsgRecord::find([
            'columns'=>'iNoId,COUNT(iRecId) as count',
            'conditions'=>'bDelete=0',
            'group'  =>'iNoId',
        ]);
        $counArr=[];
        foreach ($recs as $rec){
            $counArr[$rec->iNoId]=$rec->count;
        }
        foreach ($notices as $index => $notice) {
            $notices[$index]['iNoType'] = self::$enums['iNoType'][$notice['iNoType']];
            $notices[$index]['tTime'] = date('Y/m/d H:i', strtotime($notice['tTime']));
            $notices[$index]['count']=isset($counArr[$notice['iNoId']])? $counArr[$notice['iNoId']]:0;
        }
        return $notices;
    }

    public function getNoticeAction()
    {
        $this->view->disable();
        $more = $this->request->getPost('more', 'string');
        $userId = Main::getLoginUserInfo('userId');

        $builder = $this->modelsManager->createBuilder()
            ->columns("n.iNoId,iNoType,sTitle,tTime,sUserIds")
            ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
            ->where('n.bDelete=0')->orderBy('n.tTime desc');
        if (!$more) {
            $builder->limit(2);
        }
        if(!UserPower::checkUserPower('Msg_NoAfList_All')){  //具有全部查看权限
            $builder->andWhere('( n.iNoType=1 AND sUserIds like :userId: ) OR n.iNoType=2',array('userId'=>'%,'.$userId.',%'));
        };
        $notices = $builder->getQuery()->execute()->toArray();

        $recs=XhmsgRecord::find([
            'columns'=>'iNoId,COUNT(iRecId) as count',
            'conditions'=>'bDelete=0',
            'group'  =>'iNoId',
        ]);
        $counArr=[];
        foreach ($recs as $rec){
            $counArr[$rec->iNoId]=$rec->count;
        }
        foreach ($notices as $index => $notice) {
            $notices[$index]['iNoType'] = self::$enums['iNoType'][$notice['iNoType']];
            $notices[$index]['tTime'] = date('Y/m/d H:i', strtotime($notice['tTime']));
            $notices[$index]['count']=isset($counArr[$notice['iNoId']])? $counArr[$notice['iNoId']]:0;
        }
        return $this->sendJsonResponse($notices);
    }





    /**
     * 获取msg
     *
     * @param $type
     * @return array
     *
     * create by dale 20171215
     */
    private function getMsg($type){
        $builder=$this->modelsManager->createBuilder()
            ->columns('a.iArtId,iArtType,sTargetIds,tStartTime
                ,sTitle,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId')
            ->from(['a'=>'Admin\Models\res\XhresArticle'])
            ->where('a.bDelete=0');
        $builder->andWhere('iArtType=:iArtType:',array('iArtType'=>$type))->orderBy('tCreateDate desc');
        $builder->limit(2);
        $data = $builder->getQuery()->execute()->toArray();
        $enum=XhsysEnum::getEnumByNodeName('文章类别');

        foreach ($data as $index => $row) {
            $data[$index]['iArtType'] =$enum[$row['iArtType']];
            $data[$index]['tStartTime'] = date('Y/m/d', strtotime($row['tCreateDate']));
        }
        return $data;
    }

    /**
     * 更多消息
     *
     * created by dale 20171025
     */
    public function moreNoticeAction()
    {
        Assets::easyUIMobile();
        $this->view->pick('tp/listView');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/home/moreNotice.js');
    }



    /**
     * 获取消息列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 20171127
     *
     */
    public function getMsgAction(){
        $more = $this->request->getPost('more');
        $type = $this->request->getPost('type');
        $builder=$this->modelsManager->createBuilder()
            ->columns('a.iArtId,iArtType,sTargetIds,tStartTime
                ,sTitle,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId')
            ->from(['a'=>'Admin\Models\res\XhresArticle'])
            ->where('a.bDelete=0');
        $builder->andWhere('iArtType=:iArtType:',array('iArtType'=>$type))->orderBy('tCreateDate desc');
        if(!$more){
            $builder->limit(2);
        }
        $data=$builder->getQuery()->execute()->toArray();
        $enum=XhsysEnum::getEnumByNodeName('文章类别');
        foreach ($data as $index => $row) {
            $data[$index]['iArtType'] =$enum[$row['iArtType']];
            $data[$index]['tStartTime'] = date('Y/m/d', strtotime($row['tCreateDate']));
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 详细消息
     *
     * created by dale 20171127
     */
    public function msgDetailAction(){
        $iArtId=$this->request->getQuery('iArtId') or die('缺少参数');
        $this->view->pick('home/msgDetail');
        $builder=$this->modelsManager->createBuilder()
            ->columns('a.*')
            ->from(['a'=>'Admin\Models\res\XhresArticle'])->where('iArtId=:iArtId:',array('iArtId'=>$iArtId));
        $art = $builder->getQuery()->execute()->toArray();

        $this->view->setVars([
            'art'=>$art[0],
        ]);
    }

    /**
     * 更多消息
     *
     * created by dale 20171127
     */
    public function moreMsgAction(){
        Assets::easyUIMobile();
        $this->view->pick('tp/listView');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/home/moreMsg.js');
    }

    /**
     * 通知详情
     *
     * created by dale 20171127
     */
    public function noticeDetailAction(){
        $iNoId=$this->request->getQuery('iNoId') or die('缺少参数');
        $this->view->pick('home/noticeDetail');
        $notice=XhmsgNotice::findFirst([
            'conditions'=>'bDelete=0 AND iNoId=:iNoId:',
            'bind'=>['iNoId'=>$iNoId],
        ])->toArray();
        $notice['iNoType']=self::$enums['iNoType'][$notice['iNoType']];
        $notice['mContent']=str_replace(array("\r\n", "\r", "\n"),'<br>',$notice['mContent']);
        $notice['mContent']=str_replace(array(" ",),'&nbsp;',$notice['mContent']);
        $notice['mFooter']=str_replace(array("\r\n", "\r", "\n"),'<br>',$notice['mFooter']);
        $notice['mFooter']=str_replace(array(" ",),'&nbsp;',$notice['mFooter']);
        $this->saveRecord($iNoId);
        $this->view->setVars([
            'notice'=>$notice,
        ]);
    }

    /**
     * 保存记录
     * @param $iNoId
     * created by dale 20171127
     */
    public function saveRecord($iNoId){
        $userId=Main::getLoginUserInfo('userId');
        $obj=XhmsgRecord::findFirst([
            'conditions'=>'iNoId=:iNoId: AND iUserId=:iUserId:',
            'bind'=>['iNoId'=>$iNoId,'iUserId'=>$userId],
        ]);
        if (!$obj) {
            $obj=new XhmsgRecord();
        }
        $obj->iNoId=$iNoId;
        $obj->iUserId=$userId;
        $obj->save();
    }


    public static function runPhoneById(&$obj, $fields, $isArray)
    {
        $userIdArr = [];
        is_string($fields) and $fields = [$fields => $fields];
        if($isArray){
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, array_column($obj, $idField));
            }
            $userNameArr = XhhrmStaff::getPhoneById($userIdArr);
            foreach($obj as $index => $objOne){
                foreach($fields as $idField => $nameField){
                    if(!isset($userNameArr[$objOne[$idField]])) continue;
                    $obj[$index][$nameField] =  $userNameArr[$objOne[$idField]];
                }
            }
        }
        else{
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, $obj[$idField]);
            }
            $userNameArr = XhhrmStaff::getPhoneById($userIdArr);
            foreach($fields as $idField => $nameField){
                if(!isset($userNameArr[$obj[$idField]])) continue;
                $obj[$nameField] =  $userNameArr[$obj[$idField]];
            }
        }
    }


    public static function runStaffNameById(&$obj, $fields, $isArray)
    {
        $userIdArr = [];
        is_string($fields) and $fields = [$fields => $fields];
        if($isArray){
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, array_column($obj, $idField));
            }
            $userNameArr = XhhrmStaff::getStaffNameById($userIdArr);
            foreach($obj as $index => $objOne){
                foreach($fields as $idField => $nameField){
                    if(!isset($userNameArr[$objOne[$idField]])) continue;
                    $obj[$index][$nameField] =  $userNameArr[$objOne[$idField]];
                }
            }
        }
        else{
            foreach($fields as $idField => $nameField){
                $userIdArr = array_merge($userIdArr, $obj[$idField]);
            }
            $userNameArr = XhhrmStaff::getStaffNameById($userIdArr);
            foreach($fields as $idField => $nameField){
                if(!isset($userNameArr[$obj[$idField]])) continue;
                $obj[$nameField] =  $userNameArr[$obj[$idField]];
            }
        }
    }

}